<template>
    <div class="order-sum" v-loading="loading">
        <div>
            <span class="down-execel">
                <Poptip v-model="showFilter" placement="bottom-end">
                    <i class="el-icon-search poptip-condition-add"></i>
                    <a href="javascript:;" class='poptip-condition-add'>列表查找</a>
                    <div slot="content">
                        <Poptip v-model="showFilterCondition" placement="bottom-start" class='poptip-condition'>
                            <i class="el-icon-plus"></i>
                            <a href="javascript:;">添加过滤条件</a>
                            <div slot="content">
                                <ul>
                                    <li
                                        v-for="(item, index) in selectHead"
                                        :key="index"
                                        class='poptip-condition-item'
                                        @click="addFilterCondition(item)">
                                        {{item.label}}
                                    </li>
                                </ul>
                            </div>
                        </Poptip>
                        <el-form :model="conditionForm" @submit.native.prevent ref="conditionForm" label-width="120px" class="demo-dynamic">
                            <el-form-item
                                v-for="(condition, index) in conditionForm.condition"
                                :label="condition.label"
                                :key="condition.key"
                                :prop="'condition.' + index + '.value'"
                                :rules="{required: true, message: condition.label + '不能为空', trigger: 'blur'}">
                                <el-select
                                    v-if='condition.label === "流程人员"'
                                    v-model="condition.value"
                                    placeholder="请选择流程人员"
                                    size="small"
                                    filterable
                                >
                                    <el-option
                                        v-for="item in processOptions"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                    ></el-option>
                                </el-select>
                                <el-select
                                    v-else-if='condition.label === "代理人"'
                                    v-model="condition.value"
                                    placeholder="请选择代理人"
                                    size="small"
                                    filterable
                                >
                                    <el-option
                                        v-for="item in agentOptions"
                                        :key="item.id"
                                        :label="item | agentNumAddName"
                                        :value="item.id"
                                    ></el-option>
                                </el-select>
                                <el-input v-else size="small" v-model="condition.value" @keyup.enter.native="submitsearch('conditionForm')"></el-input>
                                <el-button @click.stop="removeDomain(condition)" size="mini">删除</el-button>
                            </el-form-item>
                        </el-form>

                        <div class="btns">
                            <el-button @click="submitsearch('conditionForm')" size="mini">查询</el-button>
                            <el-button @click="resetForm('conditionForm')" size="mini">重置</el-button>
                        </div>
                    </div>
                </Poptip>
            </span>
        </div>
        <el-table
            ref="order-table"
            :data="tableData"
            @sort-change='tableSortChange'
            show-summary
            :summary-method="getSummaries"
            border
        >
            <el-table-column
                label="ID"
                width="60"
                align="left"
            >
                <template slot-scope="scope">
                    {{(scope.$index + 1) + (current_page - 1) * per_page}}
                </template>
            </el-table-column>
            <el-table-column
                label="订单编号"
                align="left"
                prop="order_number"
                :show-overflow-tooltip="true"
                sortable="custom"
                min-width="170"
            ></el-table-column>
            <el-table-column
                min-width="100"
                label="代理人"
                align="left"
                prop="agent"
                sortable="custom"
                :show-overflow-tooltip="true"
            >
                <template slot-scope="scope">
                    <span v-if="scope.row.agent">{{scope.row.agent.name}}</span>
                    <span v-else>-</span>
                </template>
            </el-table-column>
            <el-table-column
                min-width="110"
                label="流程人员"
                align="left"
                prop="process"
                sortable="custom"
                :show-overflow-tooltip="true"
            >
                <template slot-scope="scope" >
                    <span v-if="scope.row.process">{{scope.row.process.name}}</span>
                    <span v-else>-</span>
                </template>
            </el-table-column>
            <el-table-column
                width="140"
                label="等待接单(天)"
                align="left"
                sortable="custom"
                prop="agent_order_taking"
                :show-overflow-tooltip="true"
            >
                <template slot-scope="scope">
                    <span :class="{'unfinish': scope.row.consumer_time.agent_order_taking > 2}">
                        {{scope.row.consumer_time.agent_order_taking | dayFilter}}
                    </span>
                </template>
            </el-table-column>
            <el-table-column
                width="160"
                label="代理人撰写(天)"
                align="left"
                sortable="custom"
                prop="order_writing"
                :show-overflow-tooltip="true"
            >
                <template slot-scope="scope">
                    <span :class="{'unfinish': scope.row.consumer_time.order_writing > 25}">
                        {{scope.row.consumer_time.order_writing | dayFilter}}
                    </span>
                </template>
            </el-table-column>
            <el-table-column
                width="140"
                label="案件质控(天)"
                align="left"
                sortable="custom"
                prop="order_quality"
                :show-overflow-tooltip="true"
            >
                <template slot-scope="scope">
                    {{scope.row.consumer_time.order_quality | dayFilter}}
                </template>
            </el-table-column>
            <el-table-column
                width="170"
                label="发送定稿文件(天)"
                align="left"
                sortable="custom"
                prop="agent_send_final"
                :show-overflow-tooltip="true"
            >
                <template slot-scope="scope">
                    <span :class="{'unfinish': scope.row.consumer_time.agent_send_final > 3}">
                        {{scope.row.consumer_time.agent_send_final | dayFilter}}
                    </span>
                </template>
            </el-table-column>
            <el-table-column
                width="160"
                label="发明人定稿(天)"
                align="left"
                sortable="custom"
                prop="inventor_confirm_final"
                :show-overflow-tooltip="true"
            >
                <template slot-scope="scope">
                    <span :class="{'unfinish': scope.row.consumer_time.inventor_confirm_final > 2}">
                        {{scope.row.consumer_time.inventor_confirm_final | dayFilter}}
                    </span>
                </template>
            </el-table-column>
            <el-table-column
                width="140"
                label="案件上传(天)"
                align="left"
                sortable="custom"
                prop="order_upload"
                :show-overflow-tooltip="true"
            >
                <template slot-scope="scope">
                    <span :class="{'unfinish': scope.row.consumer_time.order_upload > 3}">
                        {{scope.row.consumer_time.order_upload | dayFilter}}
                    </span>
                </template>
            </el-table-column>
            <el-table-column
                width="130"
                label="总耗时(天)"
                align="left"
                prop="consumer_time_total"
                :show-overflow-tooltip="true"
                sortable="custom"
            >
                <template slot-scope="scope">
                    <!-- <span :class="{'unfinish': getSum(scope.row.consumer_time) > 35}">
                        {{getSum(scope.row.consumer_time) > 0 ? getSum(scope.row.consumer_time) : '-'}}
                    </span> -->
                    <span :class="{'unfinish': scope.row.consumer_time.process_take_time > 35}">
                        {{scope.row.consumer_time.process_take_time | dayFilter}}
                    </span>
                </template>
            </el-table-column>
            <el-table-column
                width="160"
                label="案件提交时间"
                align="left"
                prop="created_at"
                sortable="custom"
                :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
                width="160"
                label="定稿时间"
                align="left"
                prop="finish_at"
                sortable="custom"
                :show-overflow-tooltip="true"
            >
                <template slot-scope="scope">
                    {{scope.row.finish_at || '-'}}
                </template>
            </el-table-column>
        </el-table>
        <pagination @paginationChange="paginateChange" :total="total"></pagination>
    </div>
</template>

<script>
import Pagination from '~/components/pagination'
export default {
    components: {
        Pagination
    },
    data() {
        return {
            loading: false,
            per_page: 25,
            current_page: 1,
            tableData: [],
            total: 0,
            showFilter: false,
            showFilterCondition: false,
            // 筛选条件
            conditionForm: {
                condition: []
            },
            selectHead: [
                {
                    label: '订单编号',
                    props: 'order_number',
                    is_show: true
                },
                {
                    label: '代理人',
                    props: 'agent_id',
                    is_show: true
                },
                {
                    label: '流程人员',
                    props: 'process_id',
                    is_show: true
                }
            ],
            sort_params: {},
            search_params: {},
            processOptions: [],
            agentOptions: [],
            tableSum: {},
            tableAvg: {}
        }
    },

    computed: {
        tableHeight() {
            let height = 1000
            if (process.client) {
                height = window.innerHeight - 202
            }
            return height
        },
    },

    created() {
        this.getTableData()
        this.getAllAgent()
    },

    methods: {
        getSum(data) {
            let sum = data.agent_order_taking + data.order_writing + data.order_quality + data.agent_send_final + data.inventor_confirm_final + data.order_upload
            sum = Math.floor(sum * 100) / 100
            return sum
        },
        tableSortChange(column) {
            this.sort_params = {
                sort_str: column.prop
            }
            if (column.order == 'ascending') {
                this.sort_params.sort_order = 'asc'
            } else if (column.order == 'descending') {
                this.sort_params.sort_order = 'desc'
            } else {
                this.sort_params = {}
            }
            this.getTableData()
        },
        getTableData(args) {
            let params = {
                page: this.current_page,
                perPage: this.per_page
            }
            params = {...params, ...this.sort_params, ...this.search_params}
            if (args) {
                params = {...params, ...args}
            }
            this.loading = true
            this.$axios.get('/api/order/order_consumer_time', {
                params: params
            }).then(res => {
                if (res.data.code == 200) {
                    this.loading = false
                    this.tableData = res.data.data
                    this.total = res.data.page.total
                    this.tableAvg = res.data.avg
                } else {
                    this.loading = false
                    this.$message({
                        type: 'error',
                        message: res.data.message
                    })
                }
            })
        },
        paginateChange(params) {
            this.per_page = params.perPage
            this.current_page = params.page
            this.getTableData()
        },
        addFilterCondition(item) {
            let filterItem = {
                value: '',
                label: item.label,
                parameter: item.props,
                key: Date.now()
            }

            if (this.conditionForm.condition.length > 0) {
                let conditionlabels = []
                for (let i = 0; i < this.conditionForm.condition.length; i++) {
                    conditionlabels.push(this.conditionForm.condition[i].label)
                }
                let Check = conditionlabels.indexOf(item.label)
                Check == -1 ? this.conditionForm.condition.push(filterItem) : this.$message.error('请勿重复添加')
            } else {
                this.conditionForm.condition.push(filterItem)
            }

            this.showFilterCondition = false;
        },
        removeDomain(item) {
            let index = this.conditionForm.condition.indexOf(item)
            if (index !== -1) {
                this.conditionForm.condition.splice(index, 1)
            }
            if (item.label === '提交时间') {
                this.submitTime = []
            }
            let props = JSON.parse(JSON.stringify(this.conditionForm.condition))
            console.log(props)
            let params = {}
            props.forEach(v => {
                params[v.parameter] = v.value
            })
            if (params.created_at) {
                params.createdTime = params.created_at
                delete params.created_at
            }
            this.search_params = params
            this.showFilter = false
            this.getTableData()
        },
        submitsearch(formName) {
            let that = this
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let props = JSON.parse(JSON.stringify(this.conditionForm.condition))
                    let params = {}
                    props.forEach(v => {
                        params[v.parameter] = v.value
                    })
                    if (params.created_at) {
                        params.createdTime = params.created_at
                        delete params.created_at
                    }
                    this.current_page = 1
                    this.$refs['order-table'].clearSort()
                    this.sort_params = {}
                    this.search_params = {...params}
                    this.getTableData()
                    this.showFilterCondition = false
                    this.showFilter = false
                }
            })
        },
        resetForm(formName) {
            this.conditionForm.condition.forEach(v => {
                if (v.value) {
                    v.value = null
                }
            });
            this.$refs['order-table'].clearSort()
            this.sort_params = {}
            this.search_params = {}
            this.$nextTick(() => {
                this.$refs[formName].clearValidate()
            })
            // this.getTableData()
            // this.showFilterCondition = false
            // this.showFilter = false
        },
        getAllAgent() {
            this.$axios.get('api/user/agent').then(res => {
                if (res.data.code == 200) {
                    this.agentOptions = res.data.data
                }
            }).catch(err => {
                this.$message({
                    type: "err",
                    message: err
                });
            });

            this.$axios.get('api/user/process').then(res => {
                if (res.data.code == 200) {
                    let arr = res.data.data;
                    this.processOptions = res.data.data
                }
            }).catch(err => {
                this.$message({
                    type: "err",
                    message: err
                });
            });
        },
        // // 表格末尾合计
        getSummaries (param) {
            // console.log(param)
            const { columns, data } = param
            const sums = []
            columns.forEach((column, index) => {
                if (index === 1) {
                    sums[index] = '平均耗时(天)';
                    return;
                }
                if (column.label === '等待接单(天)') {
                    sums[index] = this.tableAvg.agent_order_taking;
                }
                if (column.label === '代理人撰写(天)') {
                    sums[index] = this.tableAvg.order_writing;
                }
                if (column.label === '案件质控(天)') {
                    sums[index] = this.tableAvg.order_quality;
                }
                if (column.label === '发送定稿文件(天)') {
                    sums[index] = this.tableAvg.agent_send_final;
                }
                if (column.label === '发明人定稿(天)') {
                    sums[index] = this.tableAvg.inventor_confirm_final;
                }
                if (column.label === '案件上传(天)') {
                    sums[index] = this.tableAvg.order_upload;
                }
                if (column.label === '总耗时(天)') {
                    sums[index] = this.tableAvg.process_take_time;
                    // sums[index] = 0
                    // for (const key in this.tableAvg) {
                    //     sums[index] += this.tableAvg[key]
                    // }
                    // sums[index] = sums[index].toFixed(2)
                }
            })
            return sums
        }
    }
}
</script>

<style lang="less" scoped>
.order-sum {
    height: 100%;
    /deep/.el-table {
		.img-wrap {
			display: flex;
            justify-content: center;
            > div {
                height: 23px;
            }
			.el-image {
                width: 23px;
				height: 23px;
			}
        }
        .el-table__footer-wrapper {
            .cell {
                font-weight: bold;
                color: #333;
            }
        }
	}
    /deep/.ivu-poptip-inner {
		min-width: 450px;
		// height: 300px;
		overflow-y: scroll;
	}

	/deep/.poptip-condition .ivu-poptip-inner {
		min-width: 180px;
	}

	.demo-dynamic {
		padding-left: 10px;

		.el-form-item {
			margin-bottom: 12px;
		}

		.el-input {
			width: 240px;
		}

		.el-date-editor {
			width: 240px;
		}

		.el-button {
			padding: 9px 15px;
			vertical-align: baseline;
		}

		.el-form-item__error {
			padding-top: 0;
		}
	}

	.poptip-condition {
		display: block;
		margin-top: 10px;

		.poptip-condition-item {
			line-height: 25px;
			cursor: pointer;
		}

		.poptip-condition-add {
			font-size: 14px;
		}
	}

	.btns {
		margin-top: 10px;
    }
    .el-select {
        width: 240px;
    }
}
</style>
